<?php
namespace app\admin2\controller;

use think\Db;
use think\Session;
use app\common\controller\AdminBaseo;
use app\common\model\Csuser as CsuserModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\Users as UsersModel;

class Publicnum extends AdminBaseo
{
    protected $author_wx_user;
    protected $admin_id;
    protected $admin_user_model;
    protected $csuser_model;
    protected $users_model;

    protected function _initialize(){
        parent::_initialize();
        $this->users_model = new UsersModel();
        $this->csuser_model = new CsuserModel();
        $this->author_wx_user = new AuthorWxUserModel();
        $this->admin_user_model = new AdminUserModel();
        $this->admin_id = session::get('admin_id');
    }

    public function index(){
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user
                        ->alias('w')
                        ->field('w.id,w.wxname,w.principal_name,think_admin_user.username as admin_name')
                        ->where($where)
                        ->join('think_admin_user','w.uid = think_admin_user.id')
                        ->select();

        foreach($wechat_list as $wechat){
            $wechat['current_csuser_count'] = $this->csuser_model
                ->field("count(*) as valid_count,(SELECT count(*) FROM think_csuser where auid = {$wechat['id']} AND status = 1 AND type = 1) as online_count")
                ->where('auid',$wechat['id'])->where('status',1)->find();
            $wechat['current_subscribe_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
            $wechat['current_butt_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();

            $cs_ids = $this->csuser_model->where('auid',$wechat['id'])->where('status',1)->group('auid')->value('group_concat(id) as cs_ids');
            $wechat['current_msg_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where('send_type',1002)->whereIn('cs_id',$cs_ids)->whereTime('send_time', 'd')->count();
        }
        
        return $this->fetch('index',[
            'wechat_list' => $wechat_list,
        ]);
    }

    public function users($wechat_id){
        $admin_users = $this->admin_user_model->field('id,username')->where('status',1)->select();
        return $this->fetch('users',[
            'admin_users' => $admin_users,
            'wechat_id' => $wechat_id
        ]);
    }

    public function author($wechat_id,$uid){
        $result = $this->author_wx_user->save(['uid' => $uid],['id' => $wechat_id]);
        if($result){
            return json(['status' => 1 , 'msg' => '授权成功']);
        }else{
            return json(['status' => -1 , 'error' => '授权失败']);
        }
    }

    public function publicNumList(){
        file_put_contents('./requestMsg.log', 'fasion apply before public numlist:'.time()."\n", FILE_APPEND);
        $arr_data = [
            'type' => 'init',
            'data' => [
                'id' => $this->admin_id,
            ],
        ];
        // 发送websocket 信息
        sendWebSocket($arr_data);
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user->get_wx_list($where)->toArray();

//        file_put_contents('./requestMsg.log', 'fasion apply wechat list:'.time().$wechat_list."\n", FILE_APPEND);

        if($wechat_list){
            foreach($wechat_list as $key => $wechat){
//                file_put_contents('./requestMsg.log', 'fasion apply $wechat_list foreach += :'.time()."\n", FILE_APPEND);
                $wechat_list[$key]['current_csuser_count'] = $this->csuser_model->get_valid_count_and_online_count($wechat);
                // 从user表获取用户, 取得关注数, 速度慢, 采用写入公众号数据的形式存储数据, 然后动态更新
//                $wechat_list[$key]['current_subscribe_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
//                $wechat_list[$key]['current_butt_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();

                $cs_ids = $this->csuser_model->where('auid',$wechat['id'])->where('status',1)->group('auid')->value('group_concat(id) as cs_ids');
                $wechat_list[$key]['current_msg_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where('send_type',1002)->whereIn('cs_id',$cs_ids)->whereTime('send_time', 'd')->count();
            }

//            $len = count($wechat_list);
//            for($k = 1;$k < $len;$k++)
//            {
////                file_put_contents('./requestMsg.log', 'fasion apply $wechat_list length loading += :'.time()."\n", FILE_APPEND);
//                for($j = 0;$j < $len - $k;$j++){
//                    if($wechat_list[$j]['current_butt_count'] < $wechat_list[$j+1]['current_butt_count']){
//                        $temp =$wechat_list[$j+1];
//                        $wechat_list[$j+1] =$wechat_list[$j] ;
//                        $wechat_list[$j] = $temp;
//                    }
//                }
//            }
//            file_put_contents('./requestMsg.log', 'fasion apply end $wechat_list request:'.time()."\n", FILE_APPEND);

            return json(['status' => 1 ,'msg' => 'ok', 'wechat_list' => $wechat_list]);
        }else{
            return json(['status' => -1 ,'error' => 'error']);
        }
    }

    // 手动更新公众号当天关注数量
    public function update_subnum(){
        $reslut_array = array();
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user->get_wx_list($where)->toArray();
        foreach($wechat_list as $key => $wechat){
            // 从user表获取用户, 取得关注数, 速度慢, 采用写入公众号数据的形式存储数据, 然后动态更新
            $current_subscribe_count = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
            //  更新数据到数据库
            $current_butt_count = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();
            $data = [
                'current_subscribe_count' => $current_subscribe_count,
                'current_butt_count' => $current_butt_count
            ];
            $reslut =  $this->author_wx_user->where('id',$wechat['id'])->update($data);
//            var_dump($reslut);
            $data['result'] = $reslut;
            array_push($reslut_array,$data);
        }
        return json(['status' => 1 ,'msg' => 'ok', 'wechat_list' => $reslut]);
    }

    //  后台加载数据, 旧版本
    public function publicNumList_bk(){
        $arr_data = [
            'type' => 'init',
            'data' => [
                'id' => $this->admin_id,
            ],
        ];
        // 发送websocket 信息
        sendWebSocket($arr_data);
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user->get_wx_list($where)->toArray();
                        
        
        if($wechat_list){
            foreach($wechat_list as $key => $wechat){
                $wechat_list[$key]['current_csuser_count'] = $this->csuser_model->get_valid_count_and_online_count($wechat);
                $wechat_list[$key]['current_subscribe_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
                $wechat_list[$key]['current_butt_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();
    
                $cs_ids = $this->csuser_model->where('auid',$wechat['id'])->where('status',1)->group('auid')->value('group_concat(id) as cs_ids');
                $wechat_list[$key]['current_msg_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where('send_type',1002)->whereIn('cs_id',$cs_ids)->whereTime('send_time', 'd')->count();
            }

            $len = count($wechat_list);

            for($k = 1;$k < $len;$k++)
            {
                for($j = 0;$j < $len - $k;$j++){
                    if($wechat_list[$j]['current_butt_count'] < $wechat_list[$j+1]['current_butt_count']){
                        $temp =$wechat_list[$j+1];
                        $wechat_list[$j+1] =$wechat_list[$j] ;
                        $wechat_list[$j] = $temp;
                    }
                }
            }
            
            return json(['status' => 1 ,'msg' => 'ok', 'wechat_list' => $wechat_list]);
        }else{
            return json(['status' => -1 ,'error' => 'error']);
        }
    }

    public function adminUsersList(){
        $admin_users = $this->admin_user_model->field('id,username')->where('status',1)->select();
        if($admin_users){
            return json(['status' => 1, 'msg' => 'ok' , 'admin_users' => $admin_users]);
        }else{
            return json(['status' => -1, 'error' => 'error']);
        }
    }
}